const Utils = require('../../utils'); // 工具函数
const LinkInfoTalk = require('../../models/blog_info_talk');
const InfoTalkDesc = require('../../models/blog_info_talk_desc');

const ControllerTalk = {
    /* 列表 */
    getList: async function (req, res, next) {
        try {
            const { per_page, page } = req.query;
            const all = await LinkInfoTalk.all();
            const getComment = Utils.getData(all); //* 树形数据处理索引0为一级，其他均为子级
            const commentData = Utils.getChildrenTree(getComment, getComment[0]); //* 按父子关系处理分类
            const list = Utils.getPagination(commentData, per_page, page);

            list.sort((a, b) => {
                return a.id - b.id
            })

            res.json({ code: 200, msg: '查询完成', data: { list, total: commentData.length } })

        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    /* 添加留言 */
    Insert: async function (req, res, next) {
        try {
            let { id, content, name, mail, url } = req.body;

            let params = { content: encodeURI(content), name, created_time: new Date().getTime() };
            if (!content) return res.json({ code: 0, msg: '回复内容必须填写' });
            if (!name) return res.json({ code: 0, msg: '必须填写昵称' });
            if (mail) params.mail = mail;
            if (url) params.url = url;

            if (id) {
                const item = await LinkInfoTalk.select({ id })
                params.pid = item[0].pid ? item[0].pid : id;
                params.reply_id = id;
                params.reply_name = item[0].name;
                params.reply_content = item[0].content;
                params.reply_master = item[0].master;
            }

            await LinkInfoTalk.insert(params);

            res.json({ code: 200, msg: '发表成功' })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    getDesc: async function (req, res, next) {
        try {
            const list = await InfoTalkDesc.all();
            res.json({ code: 200, data: { list: list[0] } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    /* 回复 */
    reply: async function (req, res, next) {
        try {

            res.json({ code: 200, msg: '成功回复留言', data: {} })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
}

module.exports = ControllerTalk;